package com.jie.controller;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jie.common.BaseContext;
import com.jie.dao.AdminPageDao;
import com.jie.entity.Admin;
import com.jie.service.AdminService;
import com.jie.utility.JwtUtils;
import com.jie.utility.QueryInfo;
import com.jie.utility.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.kafka.KafkaProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import sun.security.provider.MD5;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jie
 * @since 2023-12-05
 */
@RestController
@RequestMapping("/rear-end/admin")
public class AdminController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RedisTemplate redisTemplate;
   @GetMapping("/test")
   public R<String> test(HttpServletRequest request){
       String jwt = request.getHeader("Authorization");
       if(jwt==null){
           return R.error("没有登录");
       }
       R r = JwtUtils.parseJwt(jwt);
       Map map = r.getMap();

       if(map.get("adminId").toString()==null){
           return R.error("Not Admin");
       }
       return r;
   }

    /**
     * 后台登陆
     * @param request
     * @param admin
     * @return
     */
    @PostMapping("/login")
    public R<String> login(HttpServletRequest request,@RequestBody Admin admin){
        LambdaQueryWrapper<Admin> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Admin::getUsername,admin.getUsername());
        Admin admin1 = adminService.getOne(queryWrapper);
        if(admin1==null){
            return R.error("登录失败");
        }
        if(!admin1.getPassword().equals(admin.getPassword())){
            return R.error("密码错误");
        }
        if(admin1.getStatus()==0){
            return R.error("该账号已经禁用");
        }
        request.getSession().setAttribute("adminId",admin1.getAdminId());
        String key="adminId:"+admin1.getAdminId();
        Map<String, Object> claims=new HashMap<>();
        claims.put("adminId",admin1.getAdminId());
        claims.put("username",admin1.getUsername());
        claims.put("type",admin1.getType());
        claims.put("createAdminId",admin1.getCreateAdminId());
        String jwt = JwtUtils.generateJwt(claims);
        String o = (String) redisTemplate.opsForValue().get(key);
        if(StringUtils.isNotEmpty(o)){
            redisTemplate.delete(key);
        }
        redisTemplate.opsForValue().set(key,jwt,30l , TimeUnit.MINUTES);
        return R.success(jwt,claims);
    }

    /**
     * 后台退出
     * @param request
     * @return
     */
    @GetMapping ("/logout")
    public R<String> logout(HttpServletRequest request){
        String jwt = request.getHeader("Authorization");
        R r = JwtUtils.parseJwt(jwt);
        Map map = r.getMap();
        Integer adminId= (Integer) map.get("adminId");
        String key="adminId:"+adminId;
        request.getSession().removeAttribute("adminId");
        Boolean delete = redisTemplate.delete(key);
        if(delete){
            return R.success("退出成功");
        }
        return R.success("退出成功");

    }

    /**
     * 分页查询全部用户
     * @return
     */
    @GetMapping("/selectAllAdmin")
    public R<List<Admin>> selectAllAdmin(HttpServletRequest request,  QueryInfo queryInfo ){
        String jwt = request.getHeader("Authorization");
        R r = JwtUtils.parseJwt(jwt);
        Map data =  r.getMap();
        Admin admin = new Admin();
        admin.setType(Long.valueOf((data.get("type").toString())));
        admin.setAdminId((Integer) data.get("adminId"));
        return selcetAdmin(jwt, adminService.selectAllAdmin(queryInfo,admin));

    }

    /**
     * 添加用户
     * @return
     */
    @PostMapping("/addAdmin")
    public R<String> addAdmin(@RequestBody Admin admin){
        if(StringUtils.isEmpty(admin.getPassword())||admin.getPassword().equals(' ')){
            admin.setPassword("123456");
        }
        boolean b = adminService.addadmin(admin);
        if(b){
            return R.success("添加成功");

        }
        return R.error("添加失败！");
    }

    /**
     * 修改用户信息
     * @param admin
     * @return
     */
    @PostMapping("/updateAdmin")
    public R<String> updateAdmin(@RequestBody Admin admin){
        boolean b = adminService.updateAdmin(admin);
        if(b){
            return R.success("修改成功");
        }
        return R.error("修改失败！");
}

    /**
     * 删除账号
     * @param admin
     * @return
     */
    @GetMapping("/delAdmin")
    public R<String> delAdmin( Admin admin){
        boolean b = adminService.delAdmin(admin);
        if(b){
            return R.success("删除成功");
        }
        return R.error("删除失败！");
}

    /**
     * 根据用户名查询用户信息
     * @param request
     * @param
     * @param
     * @return
     */
    @PostMapping("/selectAdmin")
    public R<List<Admin>> selectAdmin(HttpServletRequest request, @RequestBody AdminPageDao adminPageDao){
//        Admin admin = new Admin();
        String username="%"+adminPageDao.getAdmin().getUsername()+"%";
        adminPageDao.getAdmin().setUsername(username);
        String jwt = request.getHeader("Authorization");
        return selcetAdmin(jwt, adminService.selectAdmin(adminPageDao.getQueryInfo(), adminPageDao.getAdmin()));
    }

    /**
     * 查询用户信息方法
     * @param jwt
     * @param adminService 具体查询用户信息的返回值
     * @return
     */
    private R<List<Admin>> selcetAdmin(String jwt, Page adminService) {
        if(jwt ==null){
            return R.error("没有登录");
        }else {
            R r = JwtUtils.parseJwt(jwt);
            Page page = adminService;
            List<Admin> admins = new ArrayList<>();
            for (Object record : page.getRecords()) {
                Admin admin1 = JSON.parseObject(JSON.toJSONString(record), Admin.class);
                admins.add(admin1);
            }
            if (admins != null) {
                Map map = r.getMap();
                map.put("total", page.getTotal());
                return R.success(admins, map);
            }
            return R.error("没有用户信息");
        }
    }
}


